const fs = require('fs')
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default
const path = require('path')
const babel = require('@babel/core')

const getModuleInfo = (file) => {
    const body = fs.readFileSync(file, 'utf-8')
    const ast = parser.parse(body, {
        sourceType: 'module' // 告诉bundle我们代码是ES模块
    })
    // 遍历AST语法树，收集依赖
    const deps = {}

    traverse(ast, {
        ImportDeclaration({ node }) {
            const dirname = path.dirname(file)
            const absPath = './' + path.join(dirname, node.source.value)
            deps[node.source.value] = absPath
        }
    })

    // 根据ast生成低版本的js代码
    const { code } = babel.transformFromAst(ast, null, {
        presets: ['@babel/preset-env']
    })
    
    const moduleInfo = {
        file: file,
        deps: deps,
        code: code
    }
    return moduleInfo
}

const parseModules = (file) => { // 接收入口文件参数
    const entry = getModuleInfo(file)
    // 递归读取依赖
    const temp = [entry]
    
    for (let i = 0; i < temp.length; i++) {
        const deps = temp[i].deps
        if (deps) {
            for (const key in deps) {
                if (deps.hasOwnProperty(key)) {
                    const child = getModuleInfo(deps[key])
                    temp.push(child)
                }
            }
        }
    }
    
    const depsGraph = {}
    temp.forEach(moduleInfo => {
        depsGraph[moduleInfo.file] = {
            deps: moduleInfo.deps,
            code: moduleInfo.code
        }
    })

    console.log(depsGraph)
    return depsGraph // 返回依赖图
}
// 处理一下 require函数 exports对象
const bundle=(file)=>{
      const depsGraph=JSON.stringify(parseModules(file))
      (function (graph){
        function require(file){
          
        }
        require(file)
                  
      })(depsGraph)

}

// 使用方式
const entryFile = './src/index.js'
const moduleInfo = getModuleInfo(entryFile)
console.log('单个模块信息:', moduleInfo)

console.log('\n所有模块依赖图:')
const depsGraph = parseModules(entryFile) // 传递入口文件路径